import React from "react";
import { useAuth } from "context/auth-context";
import { Form, Input } from "antd";
import { LongBotton } from "unauthenticated-app";
import { useAsync } from "utils/use-async";
export const RegisterScreen = ({
  onError,
}: {
  onError: (error: Error) => void;
}) => {
  /**
   * 调用接口
   */
  const { register } = useAuth();
  const { run, isLoading } = useAsync(undefined, { throwOnError: true });
  const handleSubmit = async (values: {
    username: string;
    password: string;
    cpassword: string;
  }) => {
    try {
      if (values.password !== values.cpassword) {
        onError(new Error("两次密码输入不一致"));
        return;
      }
      await run(register(values));
    } catch (err) {
      onError(err);
    }
  };
  return (
    <Form onFinish={handleSubmit}>
      <Form.Item
        name="username"
        rules={[{ required: true, message: "请输入用户名" }]}
      >
        <Input placeholder="用户名" type="text" id={"username"} />
      </Form.Item>
      <Form.Item
        name="password"
        rules={[{ required: true, message: "请输入密码" }]}
      >
        <Input placeholder="密码" type="password" id={"password"} />
      </Form.Item>
      <Form.Item
        name="cpassword"
        rules={[{ required: true, message: "请再次输入密码" }]}
      >
        <Input placeholder="确认密码" type="password" id={"cpassword"} />
      </Form.Item>
      <Form.Item>
        <LongBotton loading={isLoading} htmlType="submit" type="primary">
          注册
        </LongBotton>
      </Form.Item>
    </Form>
  );
};
